<?php
namespace backend\models;

use Yii;
use yii\db\ActiveRecord;
use backend\models\Mobile;
use common\models\ImageThumb;
use backend\models\Menu;
use backend\models\User;


class Group extends ActiveRecord
{

    /**
     * 配置游戏数据表
     *
     * @return string
     */
    public static function tableName()
    {
        return '{{%group}}';
    }
    
    public function rules() {
        return [
            [['name'],'required']
        ];
    }
    
    public function attributeLabels()
    {
        return array(
            'name' => '分组名称',
            'mid'  => '权限',
            'channel' => '选择系统'
        );
    }
    

    /**
     * 分组显示
     * @author   li
     * @since    2015-07-29
     */
    public static function groupList() {

        $model = new Group();
        $data = $model->find()->orderBy('id desc')->asArray()->all();
        
        $mid = array();
        
        $menu = Menu::find()->asArray()->all();
        
        $user = User::find('username')->where(['status'=>1])->asArray()->all();
        foreach ($data as $key=>$value) {
            $data[$key]['mid'] = explode(',', $value['mid']);
        }
        foreach ($data as $key=>$value) {
            foreach ($value['mid'] as $k=>$v) {
                foreach ($menu as $val) {
                    if($val['id'] == $v) {
                        $data[$key]['modulename'][] = $val['name'];
                    }
                }
            }
            foreach ($user as $u=>$re) {
                if($re['gid']==$value['id']) {
                    $data[$key]['username'][] = $re['username'];
                }
            }
            unset($data[$key]['mid']);
        }
        return $data;
    }


    /**
     * 添加用户分组
     * @author li
     * @since  2015-07-29
     */
    public static function userGroupAdd() {
        $name = trim(Yii::$app->request->post('Group')['name']);
        $mid = Yii::$app->request->post('mid');
        $channel = Yii::$app->request->post('Group')['channel'];
        $channel = implode(',', $channel);
        $group = new Group();
        $group->name = $name;
        $group->mid  = '';
        $group->channel  = $channel;
        if(!empty($mid))
            $group->mid  = implode(',', $mid);
        if($group->save())
        {
            return true;
        }
        return false;
    }
    
    /**
     * 编辑用户组
     * @author  li
     * @since   2015-07-29
     * */
    public function actionEdit() {
        
    }
    
    
    public static function getName($id) {
        $data = self::find()->where(['id' => $id])->asArray()->one();
        return $data['name'];
    }

    public static function getChannel($id) {
        $data = self::find()->where(['id' => $id])->asArray()->one();
        return $data['channel'];
    }
}